package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ArticleBehaviorService;
import com.heima.common.constants.CollectionBehaviorConstant;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dto.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class ArticleBehaviorServiceImpl implements ArticleBehaviorService {
    @Autowired
    private ApCollectionMapper apCollectionMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 收藏文章
     * @param collectionBehaviorDto
     * @param request
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto collectionBehaviorDto, HttpServletRequest request) {
        //1.校验参数
        if (collectionBehaviorDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (collectionBehaviorDto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //获取用户id
        String userId = request.getHeader("userId");
        if ("0".equals(userId)) {
            return ResponseResult.errorResult(509,"请登录后再试！");
        }

        //2.将收藏文章存入数据库
        //判断收藏文章是否文章
        if (CollectionBehaviorConstant.COLLECTION.equals(collectionBehaviorDto.getOperation())) {
            //未收藏过就直接存
            ApCollection apCollection = new ApCollection();
            BeanUtils.copyProperties(collectionBehaviorDto, apCollection);
            //补充没有拷贝的属性
            apCollection.setArticleId(collectionBehaviorDto.getEntryId());
            apCollection.setCollectionTime(new Date());
            apCollectionMapper.insert(apCollection);
        } else {
            //取消收藏则删除
            apCollectionMapper.delete(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getEntryId, collectionBehaviorDto.getEntryId()));
        }

        //3.收藏行为存入Redis
        if (StringUtils.isNotEmpty(userId)) {
            String key = CollectionBehaviorConstant.COLLECTION_BEHAVIOR + userId;
            cacheService.hPut(key, collectionBehaviorDto.getEntryId()+"", JSON.toJSONString(collectionBehaviorDto));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
